package com.hdumooc.jdbc;

import com.hdumooc.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @description: 使用 JDBC 操作事务
 * @author: Jieyao Lu
 * @date: 2023/11/18 15:43
**/
public class TestJDBCTransaction {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1.获取连接
            connection = JDBCUtils.getConnection();

            // 2.开启事务
            connection.setAutoCommit(false); // 手动提交事务

            // 3.获取预处理对象 执行SQL (两次修改操作)
            // tom 账户 -500
            preparedStatement = connection.prepareStatement("UPDATE account SET money = money - ? WHERE name = ?");
            preparedStatement.setDouble(1, 500.0);
            preparedStatement.setString(2, "tom");
            preparedStatement.executeUpdate();

            // 模拟 tom 转账之后出现异常
            System.out.println(1 / 0);

            // jack 账户 +500
            preparedStatement = connection.prepareStatement("UPDATE account SET money = money + ? WHERE name = ?");
            preparedStatement.setDouble(1, 500.0);
            preparedStatement.setString(2, "jack");
            preparedStatement.executeUpdate();

            // 4.提交事务(正常情况)
            connection.commit();
            System.out.println("转账成功！！");
        } catch (SQLException e) {
            e.printStackTrace();
            // 5.出现异常就回滚事务
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            // 6.释放资源
            JDBCUtils.close(connection, preparedStatement);
        }
    }
}
